package com.cloud.servicelistenorder.controller;

import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ThreadLocalRandom;

@RestController
public class ListenController {

    private static final Map<String, SseEmitter> sseCache = new ConcurrentHashMap<>();

    /**
     * 消息推送服务，前端需支持 H5
     * @param driverId
     * @return
     * @throws Exception
     */
    @GetMapping(value = "/listen/driver/{driverId}",produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public SseEmitter listen(@PathVariable("driverId")String driverId) throws Exception{
        // 超时时间设置为3s，用于演示客户端自动重连
        SseEmitter sseEmitter = new SseEmitter(3_000L);
        // 设置前端的重试时间为1s
        sseEmitter.send(SseEmitter.event().reconnectTime(1000).data(ThreadLocalRandom.current().nextInt()));
        sseCache.put(driverId, sseEmitter);
//        System.out.println("add " + driverId);
//        sseEmitter.onTimeout(() -> {
//            System.out.println(driverId + "超时");
//            sseCache.remove(driverId);
//        });
        sseEmitter.onCompletion(() -> System.out.println("完成！！！"));
        return sseEmitter;
    }
}
